﻿using DotNetty.Buffers;
using DotNetty.Codecs.Http.WebSockets;
using DotNetty.Transport.Channels;
using System.Collections.Concurrent;

namespace DotNetty.Extensions
{
    public class WebSocketConnection
    {
        public WebSocketConnection(IChannel channel)
        {
            Channel = channel;
            Id = Channel.Id.AsShortText();
        }

        public IChannel Channel { get; }

        public string Id { get; }

        public string Name { get; set; }

        public ConcurrentDictionary<string, object> SessionItems { get; } = [];


        public async Task WriteAndFlushAsync(string text)
        {
            var frame = new TextWebSocketFrame(text);
            await Channel.WriteAndFlushAsync(frame);
        }

        public async Task WriteAndFlushAsync(IByteBuffer buffer)
        {
            var frame = new BinaryWebSocketFrame(buffer);
            await Channel.WriteAndFlushAsync(frame);
        }

        public async Task WriteAndFlushAsync(byte[] bytes)
        {
            var frame = new BinaryWebSocketFrame(Unpooled.WrappedBuffer(bytes));
            await Channel.WriteAndFlushAsync(frame);
        }

        public async Task CloseAsync()
        {
            await Channel.CloseAsync();
        }

    }
}
